package com.share.shareplatform.sharegoods.config;

import com.share.shareplatform.pojo.CommentOneLike;
import com.share.shareplatform.sharegoods.dao.CommentOneLikeDao;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
//同步数据配置
//@Component
public class ScheduleConfig {

    @Autowired
    private CommentOneLikeDao commentOneLikeDao;

    @Value("${redis.commentOneLikeRedisName}")
    private String commentOneLikeName;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    //redis同步点赞数据到mysql中
    @Scheduled(fixedDelay = 60*1000,initialDelay = 1000*10)
    public void synRedisToMysqlCommentOneLike(){

        Set<String> keys = redisTemplate.keys(commentOneLikeName + "*");
        Set<Long> longKeys=new HashSet<>(keys.size());
        ArrayList<CommentOneLike> addList=new ArrayList<>();

        for(String maxKey:keys){
            String keyString=maxKey.substring(maxKey.lastIndexOf(":")+1);
            //转成long存储
            long l = Long.parseLong(keyString);
            longKeys.add(l);

            //将所有需要添加的comment存储，到时一起添加到数据库中
            Set<Object> members = redisTemplate.opsForSet().members(maxKey);
            for(Object m:members){
                CommentOneLike commentOneLike = new CommentOneLike();
                commentOneLike.setCommentId(l);

                commentOneLike.setUserId(Long.parseLong(m+""));

                addList.add(commentOneLike);
            }
        }
        //删除
        commentOneLikeDao.deleteAllByCommentId(longKeys);
        //添加
        commentOneLikeDao.addAll(addList);

    }

}
